﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Mvc;
using WikeSoft.Core;
using WikeSoft.Core.Exception;
using WikeSoft.Core.Extension;
using WikeSoft.Data.Enum;
using WikeSoft.Enterprise.Interfaces;
using WikeSoft.Enterprise.Interfaces.WorkFlow;
using WikeSoft.Enterprise.Models;
using WikeSoft.Enterprise.Models.Filters;
using WikeSoft.WorkFlowEngine.Enum;
using WikeSoft.WorkFlowEngine.Interfaces;
using WikeSoft.WorkFlowEngine.Models;
using WikeSoft.WorkFlowEngine.Msg;

namespace WikeSoft.Web.Controllers
{
    public class HolidayController : BaseController
    {
        private readonly IHolidayApplyService _holidayService;

        private readonly IWorkFlowInstanceService _flowInstanceService;
        private readonly IWorkFlowService _workFlowService;
        public HolidayController(IHolidayApplyService holidayService, IWorkFlowInstanceService flowInstanceService, IWorkFlowService workFlowService)
        {
            _holidayService = holidayService;
            _flowInstanceService = flowInstanceService;
            _workFlowService = workFlowService;
        }

        // GET: Holiday
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetList(HolidayFilter filter)
        {
            filter.UserId = User.Identity.GetLoginUserId();
            PagedResult<HolidayModel> defs = _holidayService.GetList(filter);

           
            return JsonOk(defs);
        }

        public ActionResult Audit()
        {
            return View();
        }

        public ActionResult GetAuditList(HolidayFilter filter)
        {

            var flowInstances = _flowInstanceService.GetRuningFlowInstancesAuthority(User.Identity.GetLoginUserId());
            filter.FlowIds = flowInstances.Select(c => c.InstanceId).ToList();
            if (filter.FlowIds == null || filter.FlowIds.Count == 0)
            {
                return JsonOk(new PagedResult<HolidayModel>());
            }
            
            PagedResult<HolidayModel> defs = _holidayService.GetList(filter);

           

            return JsonOk(defs);
        }



        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(HolidayModel model)
        {
            if (ModelState.IsValid)
            {
                model.UserId = User.Identity.GetLoginUserId();
                model.Person = User.Identity.GetTrueName();
                var Id = _holidayService.Add(model);
                return Ok(new { Id = Id });

            }
            return Ok();


        }

        public ActionResult StartWorkFlow(IList<string> ids)
        {
            string userId = User.Identity.GetLoginUserId();
            var success = _holidayService.StartWorkFlow(ids, userId);
            return Ok();
        }


        public ActionResult Edit(string id)
        {
            HolidayModel model = _holidayService.Get(id);
            return View(model);
        }


        public ActionResult DetailView(string id)
        {
            HolidayModel model = _holidayService.Get(id);
            return View(model);
        }



        [HttpPost]
        public ActionResult Edit(HolidayModel model)
        {

            if (ModelState.IsValid)
            {
                model.UserId = User.Identity.GetLoginUserId();
                model.Person = User.Identity.GetTrueName();
                _holidayService.Edit(model);
                return Ok(new { Id = model.Id });

            }

            return Ok();
        }

        public ActionResult Delete(IList<string> ids)
        {
            _holidayService.Delete(ids);
            return Json(new { Code = 100, Message = "操作成功" }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult AuditDetailView(string id)
        {
            HolidayModel data = _holidayService.Get(id);
            HolidayAuditModel model = new HolidayAuditModel();
            model.InstanceId = data.FlowId;
            if (!string.IsNullOrEmpty(model.InstanceId))
            {
                TaskInstance flowInstance = _flowInstanceService.GetRunFlowInstance(model.InstanceId);
                if (flowInstance != null)
                {
                    model.TaskId = flowInstance.TaskId; 
                }
                List<TaskInstance> flows = _flowInstanceService.GetHistoryFlowInstances(model.InstanceId);
                ViewBag.Historys = flows;

            }
            return View(model);

        }

        public ActionResult WorkFlowAudit(HolidayAuditModel data, string redirectUrl)
        {
            string userId = User.Identity.GetLoginUserId();
            if (data.Agree)
            {
                HolidayModel holiday = _holidayService.Get(data.Id);
                string condition;
                if (holiday.Days >= 3)
                {
                    condition = "2";
                }
                else
                {
                    condition = "1";
                }
                WorkFlowAuthority authority = _flowInstanceService.GetNextNodeAuthority(data.TaskId, condition);
                string targetUserId = _workFlowService.GetAuthorityUser(authority, userId);
              

                AuditParams parms = new AuditParams();
                parms.NodeRecordId = data.TaskId;
                parms.UserId = userId;
                parms.UserName = User.Identity.GetTrueName();
                parms.UserMsg = data.Message;
                parms.Condition = condition;
               
                parms.TargetUserId = targetUserId;
                parms.TaskAudit = TaskAudit.Agree;

                InstanceMessage instance = _flowInstanceService.Complete(parms);
               
                if (instance.Code == CodeEum.Fail)
                {
                    throw new TipInfoException(instance.Message);
                }
                if (instance.Completed)
                {
                    if (data.Id != null)
                    {
                        _holidayService.FinishWorkFlow(data.Id);
                    }
                }
            }
            else
            {
                if (data.Id != null)
                {
                    var back = _holidayService.RejectWorkFlow(data.Id);

                    AuditParams parms = new AuditParams();
                    parms.NodeRecordId = data.TaskId;
                    parms.UserId = userId;
                    parms.UserName = User.Identity.GetTrueName();
                    parms.UserMsg = data.Message;
                    parms.Condition = string.Empty;
                    parms.TargetUserId = string.Empty;
                    parms.TaskAudit = TaskAudit.Suspend;

                    InstanceMessage instance = _flowInstanceService.Complete(parms);
                    


                }
            }
            return Redirect(redirectUrl);
        }

        public ActionResult WorkFlowAuditDetailView()
        {
            return View();
        }
    }
}